package com.globaldom.web.locations;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.globaldom.model.PersonLocation;
import com.globaldom.utils.Constants;
import com.globaldom.utils.MemCacheManager;
import com.globaldom.utils.PMF;
import com.globaldom.utils.SessionManager;

@Controller
@RequestMapping(value = "/getpersonlocation")
public class LocationGetController {

	public LocationGetController() {
	}

	// FIXME Bound this by the coordinates. Right now it gets ALL satellites.
	@RequestMapping(value = "/get", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> getMyLocation(@RequestParam float nlat, @RequestParam float nlon, @RequestParam float slat,
			@RequestParam float slon, HttpSession session, HttpServletRequest request) {
		Map<String, String> map = null;
		String personID = SessionManager.getID(request, session);
		if (null == personID) {
			map = new HashMap<String, String>();
			map.put(Constants.STATUS, "-ER");
			map.put(Constants.CODE, "401");
			return map;
		}
		map = MemCacheManager.getLocations(personID);
		if (null != map) {
			return map;
		} else {
			map = new HashMap<String, String>();
		}

		PersistenceManager pmf = PMF.get().getPersistenceManager();
		try {
			Query query = pmf.newQuery(PersonLocation.class, "person==pid");
			query.declareParameters("String pid");
			List<PersonLocation> list = (List<PersonLocation>) query.execute(personID);

			// PERF Find by map bounds
			// FIXME directly add this to map and return!! Collateral
			// Damage:Check if cacheable
			Iterator<PersonLocation> it = list.iterator();
			while (it.hasNext()) {
				PersonLocation loc = (PersonLocation) it.next();
				if (!loc.getLocationType().equals(0))
					map.put(String.valueOf(loc.getId()), loc.getLatitude() + "/" + loc.getLongitude());
			}

			MemCacheManager.putLocations(personID, map);
		} catch (Exception edea) {
			map.put(Constants.CODE, "-ER");
			map.put(Constants.DATA, "EDE");
			MemCacheManager.removeLocations(personID);
		} finally {
			pmf.close();
		}
		return map;
	}

	// initializing method
	@RequestMapping(method = RequestMethod.GET)
	public String getCreateForm(Model model, HttpSession session) {
		return "redirect:/country";
	}

}
